from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from . import models
from . import serializer
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from luffyapi.libs.al_pay import alipay
from luffyapi.utils.logger import log


class PayView(GenericViewSet, CreateModelMixin):
    """支付接口"""
    # 有下面两行配置，用户必须登录才能操作
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    queryset = models.Order.objects.all()
    serializer_class = serializer.OrderSerializer

    # 重写create方法
    def create(self, request, *args, **kwargs):
        serializers = self.get_serializer(data=request.data, context={'request': request})
        serializers.is_valid(raise_exception=True)
        self.perform_create(serializers)  # 里面就是执行了 serializers.save()
        return Response(serializers.context.get('pay_url'))


class SuccessView(APIView):
    """同步异步回调接口"""
    def get(self, request, *args, **kwargs):
        """前端同步回调"""
        out_trade_no = request.query_params.get('out_trade_no')  # 拿到订单号
        order = models.Order.objects.filter(out_trade_no=out_trade_no).first()  # 根据订单号拿到订单
        if order.order_status == 1:  # 判断订单状态
            return Response(True)
        else:
            return Response(False)

    def post(self, request, *args, **kwargs):
        """支付宝异步回调"""
        data = request.data.dict()  # request.data是支付宝发来的query_dic对象，不能修改值，就不能pop值，用.dict()转为字典对象

        querydic = request.data
        print('dict: ', data)
        print('=================')
        print(querydic)
        try:
            si = querydic.pop('sign')
            print(si)
            print('用request.data成功pop出sign')
        except:
            print('用request.data没法pop')

        out_trade_no = data.get('out_trade_no', None)  # 取订单号，取不到就是None
        gmt_payment = data.get('gmt_payment', None)  # 取支付时间，取不到就是None
        signature = data.pop('sign')
        # 验证签名
        success = alipay.verify(data, signature)
        if success and data['trade_status'] in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
            # 验证成功就修改订单状态和支付时间
            models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1, pay_time=gmt_payment)
            # 记录日志
            log.info('%s订单支付成功' % out_trade_no)
            return Response('success')  # 支付宝接口要求返回的格式
        else:
            log.info('%s订单存在问题' % out_trade_no)
            return Response('error')  # 返回任意内容，只要不是success即可
